const express = require("express");
// 导入用户模板
const userModule = require('../module/users')
const router = express.Router()
// 插件
const multer = require('multer')
// 内置模块
var fs = require('fs');


var createFolder = function (folder) {
    try {
        fs.accessSync(folder);
    } catch (e) {
        fs.mkdirSync(folder);
    }
};

// 上传图片路径
var uploadFolder = '../webr/public/upload/';
createFolder(uploadFolder);
// 通过 filename 属性定制
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, uploadFolder);    // 保存的路径，备注：需要自己创建
    },
    filename: function (req, file, cb) {
        // 将保存文件名设置为 字段名 + 时间戳，比如 logo-1478521468943
        cb(null, file.fieldname + '-' + Date.now() + '.jpg');
    }
})
// 通过 storage 选项来对 上传行为 进行定制化
var upload = multer({ storage: storage })

// 登录接口
router.post('/login', (req, res) => {

    let { username, password } = req.body.data

    userModule.findOne({ username, password }).then(data => {
        if (data) {
            res.send({
                Code: 1,
                name:data.username,
                headerImg:data.headerImg
            })
        } else {
            res.send({
                Code: 0
            })
        }

    }).catch(e => {
        res.send({
            Code: -1,
            data: '错误' + e
        })
    })

})

//注册接口
router.post('/register', upload.single('headerImg'), (req, res) => {

    let { username, password } = req.body
    // 头像图片
    const headerImg = req.file.filename

    // 利用模板创建一条数据
    let user = new userModule({
        username,
        password,
        headerImg,
    })

    // 保存数据到db
    user.save().then(() => {
        res.send({
            Code: 1,
            file: headerImg
        })
    }).catch(e => {
        res.send({
            Code: -1
        })
    })
})

module.exports = router